<template>
  <a-tabs
    v-model:activeKey="activeKey"
    hide-add
    @edit="onEdit"
    class="field-config"
    type="editable-card"
    @tab-click="handleChange"
  >
    <a-tab-pane :key="item.key" :tab="item.name" v-for="item in panes">
      <slot></slot>
    </a-tab-pane>
  </a-tabs>
</template>
<script setup lang="ts">
const props = defineProps({
  tabsList: {
    type: Array<CommonTypes.TabItem>,
    default: () => [],
  },
  tabsValue: {
    type: String,
    default: '',
  },
});

const emits = defineEmits(['changeTab', 'deleteTab']);
const panes = ref(props.tabsList);
const activeKey = ref<string>('');
const remove = (targetKey: string) => {
  let lastIndex = 0;
  panes.value.forEach((pane, i) => {
    if (pane.key === targetKey) {
      lastIndex = i - 1;
    }
  });
  panes.value = panes.value.filter((pane) => pane.key !== targetKey);
  if (panes.value.length && activeKey.value === targetKey) {
    if (lastIndex >= 0) {
      activeKey.value = panes.value[lastIndex].key;
    } else {
      activeKey.value = panes.value[0]?.key || '';
    }
  }

  if (!panes.value.length) {
    activeKey.value = '';
  }
  emits('deleteTab', panes.value);
  emits('changeTab', activeKey.value);
};

const onEdit = (targetKey: string) => {
  remove(targetKey);
};

const handleChange = (key: string) => {
  emits('changeTab', key);
};

watch(
  () => props.tabsValue,
  (newVal: any) => {
    activeKey.value = newVal;
  },
  {
    deep: true,
  },
);

watch(
  () => props.tabsList,
  (newVal: any) => {
    panes.value = newVal;
  },
  {
    deep: true,
    immediate: true,
  },
);
</script>
<style scoped lang="less">
.field-config {
  :deep(.ant-tabs-tab) {
    border: none;
    margin: 0 20px;
    padding: 20px 0;
    background-color: transparent;
  }
}
</style>
